<template>
  <div class="system-monitor">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">系统监控</h1>
        <p class="page-description">实时监控系统性能、资源使用情况和运行状态</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-switch
          v-model="autoRefresh"
          active-text="自动刷新"
          @change="handleAutoRefreshChange"
        />
      </div>
    </div>

    <!-- 系统状态概览 -->
    <div class="status-overview">
      <el-row :gutter="20">
        <el-col :span="6" v-for="metric in systemMetrics" :key="metric.key">
          <el-card class="metric-card" :class="getMetricClass(metric.status)">
            <div class="metric-content">
              <div class="metric-icon" :style="{ color: metric.color }">
                <el-icon :size="32">
                  <component :is="metric.icon" />
                </el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ metric.value }}</div>
                <div class="metric-label">{{ metric.label }}</div>
                <div class="metric-status" :class="metric.status">
                  {{ getStatusText(metric.status) }}
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 性能监控图表 -->
    <div class="performance-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>CPU使用率</span>
            </template>
            <div class="chart-container" ref="cpuChartRef" v-loading="loading"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>内存使用率</span>
            </template>
            <div class="chart-container" ref="memoryChartRef" v-loading="loading"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 网络和磁盘监控 -->
    <div class="resource-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>网络流量</span>
            </template>
            <div class="chart-container" ref="networkChartRef" v-loading="loading"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>磁盘使用情况</span>
            </template>
            <div class="disk-usage">
              <div v-for="disk in diskUsage" :key="disk.name" class="disk-item">
                <div class="disk-info">
                  <span class="disk-name">{{ disk.name }}</span>
                  <span class="disk-size">{{ disk.used }} / {{ disk.total }}</span>
                </div>
                <el-progress 
                  :percentage="disk.percentage" 
                  :stroke-width="12"
                  :status="getDiskStatus(disk.percentage)"
                />
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 系统日志 -->
    <div class="logs-section">
      <el-card>
        <template #header>
          <div class="logs-header">
            <span>系统日志</span>
            <div class="logs-controls">
              <el-select v-model="logLevel" placeholder="日志级别" style="width: 120px">
                <el-option label="全部" value="all" />
                <el-option label="错误" value="error" />
                <el-option label="警告" value="warning" />
                <el-option label="信息" value="info" />
              </el-select>
              <el-button @click="clearLogs" style="margin-left: 12px">
                <el-icon><Delete /></el-icon>
                清空日志
              </el-button>
            </div>
          </div>
        </template>
        
        <div class="logs-container">
          <el-table :data="filteredLogs" stripe max-height="300">
            <el-table-column prop="timestamp" label="时间" width="180" />
            <el-table-column prop="level" label="级别" width="80">
              <template #default="{ row }">
                <el-tag :type="getLogLevelType(row.level)" size="small">
                  {{ row.level.toUpperCase() }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="module" label="模块" width="120" />
            <el-table-column prop="message" label="消息" show-overflow-tooltip />
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button size="small" type="primary" text @click="viewLogDetail(row)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 在线用户 -->
    <div class="online-users-section">
      <el-card>
        <template #header>
          <div class="users-header">
            <span>在线用户 ({{ onlineUsers.length }})</span>
            <el-button @click="refreshOnlineUsers">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </template>
        
        <el-table :data="onlineUsers" stripe>
          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="ip" label="IP地址" width="150" />
          <el-table-column prop="location" label="地理位置" width="200" />
          <el-table-column prop="browser" label="浏览器" width="150" />
          <el-table-column prop="loginTime" label="登录时间" width="180" />
          <el-table-column prop="lastActivity" label="最后活动" width="180" />
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 'active' ? 'success' : 'warning'" size="small">
                {{ row.status === 'active' ? '活跃' : '空闲' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="logDetailVisible"
      title="日志详情"
      width="60%"
    >
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="时间">{{ currentLog.timestamp }}</el-descriptions-item>
          <el-descriptions-item label="级别">
            <el-tag :type="getLogLevelType(currentLog.level)">
              {{ currentLog.level.toUpperCase() }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="模块">{{ currentLog.module }}</el-descriptions-item>
          <el-descriptions-item label="用户">{{ currentLog.user || 'N/A' }}</el-descriptions-item>
          <el-descriptions-item label="消息" :span="2">{{ currentLog.message }}</el-descriptions-item>
          <el-descriptions-item label="详细信息" :span="2">
            <pre class="log-details">{{ currentLog.details || '无详细信息' }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  Refresh, Delete, Monitor, MemoryCard, 
  Connection, HardDisk, Warning, CircleCheck
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const autoRefresh = ref(false)
const logLevel = ref('all')
const logDetailVisible = ref(false)
const currentLog = ref(null)

// 图表引用
const cpuChartRef = ref(null)
const memoryChartRef = ref(null)
const networkChartRef = ref(null)

// 定时器
let refreshTimer = null

// 系统指标数据
const systemMetrics = ref([
  {
    key: 'cpu',
    label: 'CPU使用率',
    value: '45%',
    status: 'normal',
    color: '#409EFF',
    icon: 'Monitor'
  },
  {
    key: 'memory',
    label: '内存使用率',
    value: '68%',
    status: 'warning',
    color: '#E6A23C',
    icon: 'MemoryCard'
  },
  {
    key: 'network',
    label: '网络状态',
    value: '正常',
    status: 'normal',
    color: '#67C23A',
    icon: 'Connection'
  },
  {
    key: 'disk',
    label: '磁盘空间',
    value: '82%',
    status: 'error',
    color: '#F56C6C',
    icon: 'HardDisk'
  }
])

// 磁盘使用情况
const diskUsage = ref([
  { name: 'C盘 (系统)', used: '120GB', total: '200GB', percentage: 60 },
  { name: 'D盘 (数据)', used: '450GB', total: '500GB', percentage: 90 },
  { name: 'E盘 (备份)', used: '80GB', total: '300GB', percentage: 27 }
])

// 系统日志
const systemLogs = ref([
  {
    id: 1,
    timestamp: '2024-01-15 14:30:25',
    level: 'error',
    module: '用户认证',
    message: '用户登录失败，密码错误',
    user: 'admin',
    details: 'IP: 192.168.1.100\nUser-Agent: Mozilla/5.0...'
  },
  {
    id: 2,
    timestamp: '2024-01-15 14:28:15',
    level: 'warning',
    module: '数据库',
    message: '数据库连接池使用率过高',
    user: 'system',
    details: '当前连接数: 95/100'
  },
  {
    id: 3,
    timestamp: '2024-01-15 14:25:10',
    level: 'info',
    module: '报表系统',
    message: '用户生成月度报表',
    user: 'zhangsan',
    details: '报表类型: 销售汇总\n时间范围: 2024-01'
  }
])

// 在线用户
const onlineUsers = ref([
  {
    username: 'admin',
    ip: '192.168.1.100',
    location: '北京市',
    browser: 'Chrome 120',
    loginTime: '2024-01-15 09:00:00',
    lastActivity: '2024-01-15 14:30:00',
    status: 'active'
  },
  {
    username: 'zhangsan',
    ip: '192.168.1.101',
    location: '上海市',
    browser: 'Firefox 121',
    loginTime: '2024-01-15 10:30:00',
    lastActivity: '2024-01-15 14:25:00',
    status: 'active'
  }
])

// 计算属性
const filteredLogs = computed(() => {
  if (logLevel.value === 'all') {
    return systemLogs.value
  }
  return systemLogs.value.filter(log => log.level === logLevel.value)
})

// 方法
const refreshData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新系统指标
    updateSystemMetrics()
    
    // 重新渲染图表
    nextTick(() => {
      renderCharts()
    })
    
    ElMessage.success('数据已刷新')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value = false
  }
}

const handleAutoRefreshChange = (value) => {
  if (value) {
    refreshTimer = setInterval(refreshData, 30000) // 30秒刷新一次
    ElMessage.success('已开启自动刷新')
  } else {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
    ElMessage.info('已关闭自动刷新')
  }
}

const updateSystemMetrics = () => {
  // 模拟更新系统指标数据
  systemMetrics.value[0].value = `${Math.floor(Math.random() * 30 + 30)}%`
  systemMetrics.value[1].value = `${Math.floor(Math.random() * 20 + 60)}%`
}

const getMetricClass = (status) => {
  return `metric-${status}`
}

const getStatusText = (status) => {
  const statusMap = {
    normal: '正常',
    warning: '警告',
    error: '异常'
  }
  return statusMap[status] || '未知'
}

const getDiskStatus = (percentage) => {
  if (percentage >= 90) return 'exception'
  if (percentage >= 70) return 'warning'
  return 'success'
}

const getLogLevelType = (level) => {
  const typeMap = {
    error: 'danger',
    warning: 'warning',
    info: 'info'
  }
  return typeMap[level] || 'info'
}

const clearLogs = () => {
  systemLogs.value = []
  ElMessage.success('日志已清空')
}

const viewLogDetail = (log) => {
  currentLog.value = log
  logDetailVisible.value = true
}

const refreshOnlineUsers = () => {
  ElMessage.success('在线用户列表已刷新')
}

const renderCharts = () => {
  renderCpuChart()
  renderMemoryChart()
  renderNetworkChart()
}

const renderCpuChart = () => {
  if (!cpuChartRef.value) return

  const chart = echarts.init(cpuChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['14:20', '14:22', '14:24', '14:26', '14:28', '14:30']
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [{
      data: [35, 42, 38, 45, 41, 43],
      type: 'line',
      smooth: true,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
          { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
        ])
      },
      itemStyle: { color: '#409EFF' }
    }]
  }

  chart.setOption(option)
}

const renderMemoryChart = () => {
  if (!memoryChartRef.value) return

  const chart = echarts.init(memoryChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['14:20', '14:22', '14:24', '14:26', '14:28', '14:30']
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [{
      data: [65, 68, 70, 67, 69, 68],
      type: 'line',
      smooth: true,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(230, 162, 60, 0.3)' },
          { offset: 1, color: 'rgba(230, 162, 60, 0.1)' }
        ])
      },
      itemStyle: { color: '#E6A23C' }
    }]
  }

  chart.setOption(option)
}

const renderNetworkChart = () => {
  if (!networkChartRef.value) return

  const chart = echarts.init(networkChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['上行', '下行']
    },
    xAxis: {
      type: 'category',
      data: ['14:20', '14:22', '14:24', '14:26', '14:28', '14:30']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} MB/s'
      }
    },
    series: [
      {
        name: '上行',
        data: [2.1, 1.8, 2.3, 1.9, 2.0, 2.2],
        type: 'line',
        smooth: true,
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '下行',
        data: [8.5, 9.2, 8.8, 9.0, 8.7, 9.1],
        type: 'line',
        smooth: true,
        itemStyle: { color: '#409EFF' }
      }
    ]
  }

  chart.setOption(option)
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    renderCharts()
  })
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.system-monitor {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.header-content p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-overview {
  margin-bottom: 20px;
}

.metric-card {
  height: 120px;
  transition: all 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.metric-card.metric-normal {
  border-left: 4px solid #67C23A;
}

.metric-card.metric-warning {
  border-left: 4px solid #E6A23C;
}

.metric-card.metric-error {
  border-left: 4px solid #F56C6C;
}

.metric-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 16px;
}

.metric-icon {
  margin-right: 16px;
}

.metric-info {
  flex: 1;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.metric-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.metric-status {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
}

.metric-status.normal {
  background: #f0f9ff;
  color: #67C23A;
}

.metric-status.warning {
  background: #fdf6ec;
  color: #E6A23C;
}

.metric-status.error {
  background: #fef0f0;
  color: #F56C6C;
}

.performance-section,
.resource-section,
.logs-section,
.online-users-section {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.disk-usage {
  padding: 16px;
}

.disk-item {
  margin-bottom: 16px;
}

.disk-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.disk-name {
  font-weight: 500;
  color: #303133;
}

.disk-size {
  color: #606266;
  font-size: 14px;
}

.logs-header,
.users-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logs-controls {
  display: flex;
  align-items: center;
}

.logs-container {
  margin-top: 16px;
}

.log-detail {
  padding: 16px 0;
}

.log-details {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  white-space: pre-wrap;
  margin: 0;
}
</style>
